package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.FriendListXmlResponse
import com.promise.jokerdream.response.phone.BossData
import com.promise.jokerdream.response.phone.FriendData
import org.jsoup.Jsoup

/**
 * 好友列表XML解析器
 * 专门用于解析大乐斗好友列表相关的XML数据
 * 基于Jsoup实现
 */
class FriendListXmlParser : BaseXmlParser<FriendListXmlResponse>() {
    
    /**
     * 解析好友列表XML数据
     * @param xmlString XML字符串
     * @return 解析结果
     */
    fun parseFriendListXml(xmlString: String): XmlParseResult<FriendListXmlResponse> {
        return parseXml(xmlString)
    }
    
    /**
     * 实现基类的具体解析逻辑
     * @param xmlString XML字符串
     * @return 解析后的好友列表数据
     */
    override fun doParse(xmlString: String): FriendListXmlResponse {
        val extractedData = mutableMapOf<String, Any>()
        
        try {
            val doc = Jsoup.parse(xmlString)
            val divElement = doc.selectFirst("div#id")
            
            if (divElement != null) {
                val html = divElement.html()
                parseDivContent(html, extractedData)
            }
        } catch (e: Exception) {
            // 解析失败，返回空数据
        }
        
        return FriendListXmlResponse(
            actionResult = extractedData["actionResult"] as? String ?: "",
            currentVitality = extractedData["vitality"] as? String ?: "0/100",
            xiaList = extractedData["xiaList"] as? List<BossData> ?: emptyList(),
            friendList = extractedData["friendList"] as? List<FriendData> ?: emptyList(),
            currentPage = extractedData["currentPage"] as? Int ?: 1,
            totalPages = extractedData["totalPages"] as? Int ?: 1
        )
    }
    
    /**
     * 解析div内容
     */
    private fun parseDivContent(html: String, data: MutableMap<String, Any>) {
        val normalizedHtml = html.replace(Regex("<br\\s*/?>"), "<br/>")
        val doc = Jsoup.parse(normalizedHtml)
        val divElement = doc.selectFirst("div#id")

        // 提取体力值
        val vitalityRegex = Regex("当前体力值：([^\\s]+)")
        val vitalityMatch = vitalityRegex.find(html)
        if (vitalityMatch != null) {
            data["vitality"] = vitalityMatch.groupValues[1]
        }
        
        // 提取分页信息
        val pageRegex = Regex("第(\\d+)/(\\d+)页")
        val pageMatch = pageRegex.find(html)
        if (pageMatch != null) {
            data["currentPage"] = pageMatch.groupValues[1].toInt()
            data["totalPages"] = pageMatch.groupValues[2].toInt()
        }
        
        // 解析侠数据
        val bossList = mutableListOf<BossData>()
        // 解析好友数据
        val friendList = mutableListOf<FriendData>()

        // 按行分割内容
        val lines = normalizedHtml.split("<br/>")
        for (line in lines) {
            val trimmedLine = line.trim()
            if (trimmedLine.isEmpty()) continue
            
            // 解析侠数据
            if (trimmedLine.contains("侠：")) {
                val bossData = parseBossData(trimmedLine)
                if (bossData != null) {
                    bossList.add(bossData)
                }
            }
            // 解析好友数据（带编号的）
            else if (trimmedLine.matches(Regex("\\d+：.*"))) {
                val friendData = parseFriendData(trimmedLine)
                if (friendData != null) {
                    friendList.add(friendData)
                }
            }
        }
        
        data["xiaList"] = bossList
        data["friendList"] = friendList
    }
    
    /**
     * 解析侠数据
     */
    private fun parseBossData(lineText: String): BossData? {
        return try {
            // 匹配名称链接
            val nameRegex = Regex("侠：.*?<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("</a>\\s*(\\d+)级")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val isFoughtRegex = Regex("已乐斗")
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            val isFought = isFoughtRegex.containsMatchIn(lineText)
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                BossData(
                    name = nameMatch.groupValues[1].replace("&nbsp;", "").trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析好友数据
     */
    private fun parseFriendData(lineText: String): FriendData? {
        return try {
            // 匹配编号前缀：1：、2：等
            val numberRegex = Regex("(\\d+)：")
            val numberMatch = numberRegex.find(lineText)
            val number = numberMatch?.groupValues?.get(1) ?: ""
            
            // 匹配VIP图标（可选）
            val vipRegex = Regex("<img[^>]*vip[^>]*>")
            val hasVip = vipRegex.containsMatchIn(lineText)
            
            // 匹配名称链接
            val nameRegex = Regex("<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("(\\d+)级\\s*")
            val factionRegex = Regex("级\\s*([^\\s<]+)")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val recruitUrlRegex = Regex("<a[^>]*href=\"([^\"]*sfight[^\"]*)\"[^>]*>")
            val isFoughtRegex = Regex("已乐斗")
            val specialSkillRegex = Regex("神拳")
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val factionMatch = factionRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            val recruitUrlMatch = recruitUrlRegex.find(lineText)
            val isFought = isFoughtRegex.containsMatchIn(lineText)
            val specialSkill = specialSkillRegex.find(lineText)?.value
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                FriendData(
                    name = nameMatch.groupValues[1].replace("&nbsp;", "").trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    faction = factionMatch?.groupValues?.get(1) ?: "",
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought,
                    recruitUrl = recruitUrlMatch?.groupValues?.get(1) ?: "",
                    specialSkill = specialSkill
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
}
